package com.shanghaionstar.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import com.onstar.cn.common.jsBridge.BridgeWebView;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.user.ActionSheet;
import com.shanghaionstar.utils.DevelopServerEnvironmentUtil;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Mengzhou Gu on 2016/8/9.
 */
public class WithActionSheetHelper implements ActionSheet.ActionSheetListener {
    private static final int CAMERA = 0x01;
    private static final int PICTURE = 0x02;
    private static final int CROP = 0x03;
    private final static int DEF_HEIGHT = 185;
    private final static int DEF_WIDTH = 185;
    private static Uri mUri;
    private String PHOTO_FILE_NAME = "";
    public static final int SHOW_ACTION_SHEET = 0x100;
    private BaseActivity mActivity;


    public WithActionSheetHelper(BaseActivity mActivity) {
        this.mActivity = mActivity;
        mActivity.setTheme(R.style.ActionSheetStyleIOS7);
    }

    /**
     * 显示ActionSheet表单
     */
    public void showDialogToTakeChoosePicture() {
        ActionSheet.createBuilder(mActivity, mActivity.getSupportFragmentManager()).setCancelButtonTitle(mActivity.getString(R.string.cancel))
                .setOtherButtonTitles(mActivity.getString(R.string.option_take_photo), mActivity.getString(R.string.option_open_album))
                .setCancelableOnTouchOutside(true).setListener(this).show();
    }


    @Override
    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

    }

    @Override
    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
        switch (index) {
            case 0:
                exeTakePhoto();
                break;
            case 1:
                exeOpenAlbum();
                break;
            default:
                break;
        }
    }

    /*
   * 从相机获取
   */
    public void exeTakePhoto() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            PHOTO_FILE_NAME = new Date().getTime() + "_temp_photo.jpg";
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
        }
        mActivity.startActivityForResult(intent, CAMERA);
    }

    /**
     * 打开相册
     */
    protected void exeOpenAlbum() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/png;image/jpg;image/jpeg");
        mActivity.startActivityForResult(pickIntent, PICTURE);
    }

    private boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CAMERA:
                    cropOnCamera();
                    break;
                case PICTURE:
                    if (null != data) {
                        Uri uri = data.getData();
                        crop(uri, DEF_WIDTH, DEF_HEIGHT);
                    }
                    break;
                case CROP:
                    handleCropData();
                    break;
                default:
                    break;
            }
        }

    }


    private void callBack(String url) {
        if (mActivity instanceof CommonWebViewActivity) {
            BridgeWebView webview = ((CommonWebViewActivity) mActivity).getWebview();
            webview.callHandler("resultCamera", url, null);
        }
    }


    private void cropOnCamera() {
        if (hasSdcard()) {
            File tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
            crop(Uri.fromFile(tempFile), DEF_WIDTH, DEF_HEIGHT);
        } else {
            Toast.makeText(mActivity, R.string.onstar_no_sdcard, Toast.LENGTH_SHORT).show();
        }
    }


    String filePath = "";
    String extension = "";

    protected void handleCropData() {
        try {
            extension = "png";
            if (!TextUtils.isEmpty(PHOTO_FILE_NAME)) {
                filePath = mUri.getPath();
                PHOTO_FILE_NAME = "";
            } else {
                filePath = getAbsoluteImagePath(mUri);
            }
            if (filePath != null) {
                extension = filePath.substring(filePath.lastIndexOf(".") + 1);
            }
            uploadImg();
        } catch (Exception e) {

        }
    }

    public static final String UPLOAD_URL_SURFIX = "/mweb/mweb-main-rest/api/v1/banner/updateFile";
    public static final String DEVELOP_BASE_URL = "https://idt1.onstar.com.cn";
    public static final String RELEASE_BASE_URL = "https://www.onstar.com.cn";

//    public String getUrl() {
//        if (DevelopServerEnvironmentUtil.getInstance().isDevelopMode(mActivity)) {
//            return DEVELOP_BASE_URL + UPLOAD_URL_SURFIX;
//        }
//        return RELEASE_BASE_URL + UPLOAD_URL_SURFIX;
//    }

    private void uploadImg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpFileUploader uploader = new OkHttpFileUploader();
                    Response mResponse = uploader.uploadImgFile(Constants.CURRENT_PREFIX_H5_URL + UPLOAD_URL_SURFIX, filePath, extension);
                    LogManager.getInstance().d(mResponse.code() + ":" + mResponse.body());
                    String body =  mResponse.body().string();
                    JSONObject obj = new JSONObject(body);
                    String url = obj.getString("url");
                    if (!TextUtils.isEmpty(url))
                        callBack(url);
                } catch (IOException e) {
                    LogManager.getInstance().e(e.getMessage());
                } catch (JSONException e) {
                    LogManager.getInstance().e(e.getMessage());
                } catch (Exception e) {
                    LogManager.getInstance().e(e.getMessage());
                }
            }
        }).start();
    }

    private void crop(Uri uri, int width, int height) {
        mUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", height);
        // intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //        intent.putExtra("noFaceDetection", true); // no face detection
        mActivity.startActivityForResult(intent, CROP);
    }

    /**
     * @param uri
     * @return 根据uri获取后缀名称
     */
    @SuppressWarnings("deprecation")
    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = mActivity.managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

}
